package org.sky.wall.visual.service

import android.app.WallpaperManager
import android.content.Intent
import android.util.Log
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.random.Random

class WallpaperService : LifecycleService() {
	private var wallpaperChangeInterval = 300_000L // 默认间隔为10秒
	
	override fun onCreate() {
		super.onCreate()
		lifecycleScope.launch {
			while (true) {
				delay(wallpaperChangeInterval)
				Log.d("xianban", "切换壁纸")
				changeWallpaper()
			}
		}
	}
	override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
		if (intent != null && intent.hasExtra("interval")) {
			wallpaperChangeInterval = intent.getLongExtra("interval", 10_000L)
		}
		
		// 在此执行其他 onStartCommand 的逻辑
		
		return super.onStartCommand(intent, flags, startId)
	}
	private fun changeWallpaper() {
		val resourceName = "a" + (Random.nextInt(1, 27))
		val resourceId = resources.getIdentifier(resourceName, "drawable", packageName)
		if (resourceId != 0) {
			val wallpaperManager = WallpaperManager.getInstance(applicationContext)
			try {
				wallpaperManager.setResource(resourceId)
			} catch (e: Exception) {
				Log.e("WallpaperService", "设置壁纸时出错: ${e.message}")
			}
		}
	}
	
	fun setWallpaperChangeInterval(intervalMillis: Long) {
		wallpaperChangeInterval = intervalMillis
	}
	
	override fun onDestroy() {
		super.onDestroy()
		Log.d("xianban", "服务结束")
	}
}

